<?php
// 后台登录
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    // 登录显示
    public function index()
    {
        // 判断是否登录
        if (auth()->check()) {
            // 已登录则跳转index
            return redirect(route('admin.index'));
        }
        return view('admin.login.login');
    }

    // 登录  admin.login
    public function login(Request $request)
    {
        //表单验证  返回值是获取到的数据   无token
        $validate = $this->validate($request, [
            'username' => 'required',
            'password' => 'required'
        ]);
        // 账号密码验证
        $bool = auth()->attempt($validate);
        if ($bool === true) {
            // 当前登录的用户模型对象  , 存储在session 中
            // $model = auth()->user();
            // dump($model->toArray());
            //dump(auth()->user()->username);
            if (config('rbac.super') != auth()->user()->username) {
                // 得到当前用户的权限  user->role->nodes
                $nodes  = auth()->user()->role->nodes()->pluck('id', 'name')->toArray();
                $routes = auth()->user()->role->nodes()->pluck('router_name', 'id')->toArray();
                // 把权限保存到session
                session(['admin_nodes' => $nodes]);
                session(['admin_routes' => $routes]);
            } else {
                session(['admin_nodes' => true]);
                session(['admin_routes' => true]);
            }
            // dump(session('admin_nodes'));

            // 跳转
            return redirect(route('admin.index'));
        }
        return redirect(route('admin.login'))->withErrors(['error' => '登录失败']);
    }

    // 退出登录
    public function logout()
    {
        // 用户退出 清空session
        auth()->logout();
        return redirect(route('admin.login'))->with(['success' => '欢迎登录']);
    }
}
